package com.sixbro.data.elasticsearch.api;

import com.sixbro.data.elasticsearch.model.Article;
import com.sixbro.data.elasticsearch.repository.ArticleRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021-12-14 17:59
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    private final ArticleRepository articleRepository;
    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    public ArticleController(ArticleRepository articleRepository, ElasticsearchRestTemplate elasticsearchRestTemplate) {
        this.articleRepository = articleRepository;
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }

    @GetMapping("/findByTitleOrContentPage")
    public List<Article> findByTitleOrContentPage(String title, String content, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return articleRepository.findByTitleOrContent(title, content, pageable);
    }

//    @GetMapping("/findByTitleOrContentPageByTemplate")
//    public List<Article> findByTitleOrContentPageByTemplate(String title, String content, Integer pageNum, Integer pageSize) {
//        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
//                .withQuery(QueryBuilders.queryStringQuery(title).defaultField("title"))
//                .withQuery(QueryBuilders.queryStringQuery(content).defaultField("content"))
//                .withPageable(PageRequest.of(pageNum, pageSize))
//                .build();
//        return elasticsearchRestTemplate.bulkIndex(nativeSearchQuery, Article.class);
//    }
}
